<template>
  <el-checkbox-group :class="{ 'no-event': readonly }" v-model="multipleValue" @change="handleChange">
    <el-checkbox v-for="item in options" :key="item.value" :label="item.title" :value="item.value"></el-checkbox>
    <el-row>
      <el-col :lg="11" :xl="8">
        <el-input
          v-if="otherOption.other.type === 'textarea' && hasOther"
          type="textarea"
          placeholder="please input.."
          :rows="5"
          :autosize="{ minRows: 4 }"
          :readonly="readonly"
          maxlength="200"
          resize="none"
          @input="handleInput"
          v-model="otherValue"
        />
      </el-col>
    </el-row>
  </el-checkbox-group>
</template>

<script>
export default {
  name: "MultipleBox",
  props: {
    value: {
      type: Array,
      default: function () {
        return [];
      },
    },
    options: {
      type: Array,
      default: function () {
        return [];
      },
    },
    readonly: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      multipleValue: [],
      otherValue: "",
    };
  },
  mounted() {
    this.initData(this.value);
  },
  watch: {
    value(newArr) {
      this.initData(newArr);
    },
  },
  computed: {
    otherOption() {
      return this.options.find(i => i.other);
    },
    hasOther() {
      return this.multipleValue.includes(this.otherOption.value);
    },
    composeValue() {
      const copy = [...this.multipleValue];
      if (this.hasOther) {
        const idx = copy.indexOf(this.otherOption.value);
        copy[idx] = {
          k: this.otherOption.value,
          v: this.otherValue,
        };
      }
      return copy;
    },
  },
  methods: {
    initData(newArr) {
      let multipleValue = [];
      newArr.forEach(i => {
        if (i && i.k) {
          multipleValue.push(i.k);
          // 给 otherValue 赋值
          this.otherValue = i.v;
        } else {
          multipleValue.push(i);
        }
      });
      // 给数组赋值
      this.multipleValue = multipleValue;
    },
    handleChange(v) {
      this.$emit("input", this.composeValue);
    },
    handleInput(v) {
      this.$emit("input", this.composeValue);
    },
  },
};
</script>

<style></style>
